using System.Data;
using System.Web.Mvc;
using Rhino.Commons;

namespace Kym.Web
{
    public class TransactionAttribute : ActionFilterAttribute
    {
        private RhinoTransaction transaction;
        private IUnitOfWork uow;
        private UnitOfWorkNestingOptions nestingOptions = UnitOfWorkNestingOptions.ReturnExistingOrCreateUnitOfWork;
        private IsolationLevel isolationLevel = IsolationLevel.ReadCommitted;

        public UnitOfWorkNestingOptions NestingOptions
        {
            get { return nestingOptions; }
            set { nestingOptions = value; }
        }

        public IsolationLevel IsolationLevel
        {
            get { return isolationLevel; }
            set { isolationLevel = value; }
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            uow = UnitOfWork.Start(NestingOptions);

            if (!UnitOfWork.Current.IsInActiveTransaction)
                transaction = UnitOfWork.Current.BeginTransaction(IsolationLevel);
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (transaction != null)
            {
                if (filterContext.Exception == null)
                    transaction.Commit();
                else
                    transaction.Rollback();

                transaction.Dispose();
            }

            uow.Dispose();
        }
    }
}